#include "imhistorymgrdlg.h"
#include "ui_imhistorymgrdlg.h"
#include "htmlformathelper.h"

#include <QDateTime>
#include <QDesktopServices>
 #include <QSyntaxHighlighter>

static QStringList s_all_dates;

IMHistoryMgrDlg::IMHistoryMgrDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::IMHistoryMgrDlg)
{
    ui->setupUi(this);
    Qt::WindowFlags flags = Qt::Window;
    setWindowFlags(flags | Qt::WindowCloseButtonHint|
                   Qt::WindowMinimizeButtonHint|Qt::WindowMaximizeButtonHint);

    s_all_dates.push_back("Today");
    s_all_dates.push_back("In a Week");
    s_all_dates.push_back("In a Month");

    QObject::connect(ui->filter_config, SIGNAL(currentIndexChanged(int)), SLOT(FilterConfigChanged(int)));
    QObject::connect(ui->contact_list, SIGNAL(currentTextChanged(QString)), SLOT(FilterSelected(QString)));
    QObject::connect(ui->history_View, SIGNAL(anchorClicked(QUrl)), SLOT(OnAnchorClicked(QUrl)));
    m_searched = false;
}

IMHistoryMgrDlg::~IMHistoryMgrDlg()
{
    delete ui;
}

void IMHistoryMgrDlg::InitContactList(const QStringList& allcontacts)
{
    ui->contact_list->clear();

    //m_all_contacts = allcontacts;
}

void IMHistoryMgrDlg::OnAnchorClicked(QUrl url)
{
    QString str_url = url.toString();
    if(str_url.indexOf("#userid") == 0)
    {

    }
    else
    {
        QDesktopServices::openUrl(url);
    }
}

void IMHistoryMgrDlg::InitHistoryData(MsgBusParam param)
{
    ui->filter_config->setCurrentIndex(0);
    Param2CustomType(param, m_all_history);
    size_t nums = m_all_history.size();
    QString htmlStr;
    m_all_contacts.clear();
    for(size_t i = 0; i < nums; i++)
    {
        const IMTextMessage& msg = m_all_history[i];
        QString timestr = HtmlFormatHelper::FormatTime(msg.time_);

        std::string msguid;
        // append message to message viewer
        if(msg.bsend_)
        {
            htmlStr += QString("<br/>%1 to me: %2 <br/> %3 %4 ")
                    .arg(HtmlFormatHelper::FormatUserId(msg.fromuid_))
                    .arg(timestr)
                    .arg(HtmlFormatHelper::FormatMessageContent(msg.text_))
                    .arg(HtmlFormatHelper::FormatAllPicturesToHtml(msg.message_));

            msguid = msg.fromuid_;
        }
        else
        {
            htmlStr += QString("<br/>I to %1 : %2 <br/> %3 ")
                    .arg(HtmlFormatHelper::FormatUserId(msg.id_))
                    .arg(timestr)
                    .arg(HtmlFormatHelper::FormatMessageContent(msg.text_));
            msguid = msg.id_;
        }
        m_all_contacts.push_back(QString::fromStdString(msguid));
    }
    m_all_contacts.removeDuplicates();
    //printf("received the history data. %s\n", htmlStr.toStdString().c_str());
    ui->history_View->setHtml(htmlStr);
    ui->history_View->reload();
    m_all_html = htmlStr;
    m_searched = false;
}

void IMHistoryMgrDlg::FilterConfigChanged(int selindex)
{
    ui->contact_list->clear();
    if(selindex == 0)
    {
        ui->history_View->setHtml(m_all_html);
        ui->history_View->reload();
        m_searched = false;
    }
    else if(selindex == 1)
    {
        ui->contact_list->addItems(m_all_contacts);
    }
    else if(selindex == 2)
    {
        ui->contact_list->addItems(s_all_dates);
    }
}
QString IMHistoryMgrDlg::IMMessageToHtml(const IMTextMessage &msg)
{
    QString htmlStr;
    QString timestr = HtmlFormatHelper::FormatTime(msg.time_);

    std::string msguid;
    // append message to message viewer
    if(msg.bsend_)
    {
        htmlStr += QString("<br/>%1 to me: %2 <br/> %3 %4 <br/>")
                .arg(HtmlFormatHelper::FormatUserId(msg.fromuid_))
                .arg(timestr)
                .arg(HtmlFormatHelper::FormatMessageContent(msg.text_))
                .arg(HtmlFormatHelper::FormatAllPicturesToHtml(msg.message_));
        msguid = msg.fromuid_;
    }
    else
    {
        htmlStr += QString("<br/>I to %1 : %2 <br/> %3 ")
                .arg(HtmlFormatHelper::FormatUserId(msg.id_))
                .arg(timestr)
                .arg(HtmlFormatHelper::FormatMessageContent(msg.text_));
        msguid = msg.id_;
    }
    return htmlStr;
}

void IMHistoryMgrDlg::FilterSelected(const QString& name)
{
    if(name.length() == 0)
        return;
    size_t nums = m_all_history.size();
    QString htmlStr;
    m_searched = false;
    if(ui->filter_config->currentIndex() == 1)
    {
        // by user name
        for(size_t i = 0; i < nums; i++)
        {
            const IMTextMessage& msg = m_all_history[i];
            if( ( QString::fromStdString(msg.fromuid_) != name ) &&
                    ( QString::fromStdString(msg.id_) != name ) )
            {
                continue;
            }

            htmlStr += IMMessageToHtml(msg);
        }

        ui->history_View->setHtml(htmlStr);
        ui->history_View->reload();
    }
    else if(ui->filter_config->currentIndex() == 2)
    {
        QDateTime t = QDateTime::currentDateTime();
        t = t.toUTC();
        if(name == s_all_dates[0])
        {
            t = t.addDays(-1);
        }
        else if(name == s_all_dates[1])
        {
            t = t.addDays(-7);
        }
        else if(name == s_all_dates[2])
        {
            t = t.addMonths(-1);
        }
        // by date
        for(size_t i = 0; i < nums; i++)
        {
            const IMTextMessage& msg = m_all_history[i];
            //printf("date filer:%u, msg date:%u\n", t.toTime_t(), msg.time_);
            if( t.toTime_t()  > msg.time_)
                continue;

             htmlStr += IMMessageToHtml(msg);
        }

        ui->history_View->setHtml(htmlStr);
        ui->history_View->reload();
    }
}

void IMHistoryMgrDlg::on_searchEdit_returnPressed()
{
    QString searchstr = ui->searchEdit->text();
    int searchlen = searchstr.length();

    if(searchstr == "")
        return;
    // first filter message
    size_t nums = m_all_history.size();
    QString htmlStr;

    QString name;
    if(ui->contact_list->currentItem())
        name = ui->contact_list->currentItem()->text();
    bool filtername = false;
    bool filterdate = false;
    if(ui->filter_config->currentIndex() == 1)
    {
        if(name.length() > 1)
            filtername = true;
    }
    else if(ui->filter_config->currentIndex() == 2)
    {
        if(name.length() > 1)
            filterdate = true;
    }

    QDateTime t = QDateTime::currentDateTime();
    if(filterdate)
    {
        t = t.toUTC();
        if(name == s_all_dates[0])
        {
            t = t.addDays(-1);
        }
        else if(name == s_all_dates[1])
        {
            t = t.addDays(-7);
        }
        else if(name == s_all_dates[2])
        {
            t = t.addMonths(-1);
        }
    }
    //
    size_t matchnums = 0;
    for(size_t i = 0; i < nums; i++)
    {
        const IMTextMessage& msg = m_all_history[i];
        if(filterdate)
        {
            //printf("date filer:%u, msg date:%u\n", t.toTime_t(), msg.time_);
            if( t.toTime_t()  > msg.time_)
                continue;
        }
        if(filtername)
        {
            if( ( QString::fromStdString(msg.fromuid_) != name ) &&
                    ( QString::fromStdString(msg.id_) != name ) )
            {
                continue;
            }
        }
        if( !QString::fromStdString(msg.text_).contains(searchstr, Qt::CaseInsensitive))
        {
            continue;
        }
        htmlStr += IMMessageToHtml(msg);
        matchnums++;
    }
    if(matchnums == 0)
        htmlStr = "no matching message, please research with other keyword.";
    ui->history_View->setHtml(htmlStr);
    ui->history_View->reload();
    if(matchnums == 0)
        return;
    QTextDocument *doc = ui->history_View->document();

    if(m_searched)
        doc->undo();

    QTextCursor hicursor(doc);
    QTextCursor cursor(doc);
    cursor.beginEditBlock();
    QTextCharFormat plainFormat(hicursor.charFormat());
    QTextCharFormat hilightFormat = plainFormat;
    hilightFormat.setForeground(Qt::red);

    while( !hicursor.isNull() && !hicursor.atEnd() )
    {
        hicursor = doc->find(searchstr, hicursor);
        if(!hicursor.isNull())
        {
            //hicursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, searchlen);
            hicursor.mergeCharFormat(hilightFormat);
        }
    }
    cursor.endEditBlock();
    m_searched = true;
}
